package com.partner.share.work.web.admin.web.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.partner.share.work.commons.utils.CookieUtils;
import com.partner.share.work.email.service.EmailService;
import com.partner.share.work.redis.utils.RedisUtil;
import com.partner.share.work.web.admin.entity.User;
import com.partner.share.work.web.admin.service.UserService;
import com.partner.share.work.web.admin.web.bean.RegisterDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.mail.MessagingException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author pengyangyan
 * @version 1.0.0
 * @date 2019年09月18日 13:51:00
 */
@Controller
public class LoginController {

    @Resource
    EmailService emailService;
    @Autowired
    UserService userService;
    @Autowired
    DefaultKaptcha defaultKaptcha;

    @GetMapping(value = "/login")
    public String login(Model model,HttpServletRequest request){
        String user = CookieUtils.getCookieValue(request, "user");
        if (user!=null){
            User user1 = (User) JSON.parse(user);
            model.addAttribute("email",user1.getEmail());
            model.addAttribute("password",user1.getPassword());
            model.addAttribute("isRemember",true);
        }
        return "login";
    }

    @GetMapping(value = "/loginout")
    public String loginOut(){
        return "login";
    }

    @PostMapping("/login")
    public String loginIn(User user, Model model,HttpServletResponse response,HttpServletRequest request){
        RedisUtil redisUtil = new RedisUtil();
        User one = userService.getUserByEmail(user.getEmail());
        redisUtil.setKey("email",user.getEmail());
        if (one==null){
            model.addAttribute("message","暂无该用户，请前往注册");
        }else {
            if (user.getPassword().equals(one.getPassword())){
                if ("".equals(user.getIsRemember())){
                    CookieUtils.setCookie(request,response,"user", JSON.toJSONString(user));
                    request.getSession().setAttribute("user",user);
                }
                return "index";
            }else {
                model.addAttribute("message","密码错误");
            }
        }
        return "login";
    }


    /**
     *  注册用户
     * @param registerDTO 注册实体
     * @return 登陆页面
     */
    @PostMapping("/register")
    public String register(RegisterDTO registerDTO, HttpServletRequest request,HttpServletResponse response,Model model) {
        String code = CookieUtils.getCookieValue(request, "code");
        if (code.equals(registerDTO.getCode())){
            QueryWrapper<User> queryWrapper = new QueryWrapper();
            queryWrapper.lambda().eq(User::getEmail,registerDTO.getEmail());
            User one = userService.getOne(queryWrapper);
            if (one!=null){
                model.addAttribute("message","该邮箱已注册");
                return "register";
            }else {
                User user = new User();
                user.setEmail(registerDTO.getEmail());
                user.setPassword(registerDTO.getPassword());
                userService.save(user);
                return "login";
            }
        }else {
            model.addAttribute("message","验证码错误");
            return "register";
        }
    }

    /**
     * 获取验证码
     * @param email 注册邮箱
     * @param request request
     * @param response response
     * @return 是否成功
     */
    @GetMapping("/getCode")
    @ResponseBody
    public int getCode(@RequestParam("email") String email,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException, MessagingException {
        int result = 0;
        String rule = "[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?";
        Pattern pattern;
        Matcher matcher;
        pattern = Pattern.compile(rule);
        matcher = pattern.matcher(email);
        if (matcher.matches()){
            String code = emailService.getEmailCode();
            CookieUtils.setCookie(request,response,"code",code,60);
            emailService.sendEmailTemplate(code,email);
            result = 1;
        }
        return result;
    }

    /**
     * 返回注册页面
     * @return 返回注册页面
     */
    @GetMapping("/register")
    public String registerIndex(){
        return "register";
    }

    //获取验证码
    @GetMapping("/getCoder")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            httpServletRequest.getSession().setAttribute("vrifyCode", createText);
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =
                httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    //验证码验证
    @GetMapping("/checkCode")
    @ResponseBody
    public boolean imgvrifyControllerDefaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){
        String captchaId = (String) httpServletRequest.getSession().getAttribute("vrifyCode");
        String parameter = httpServletRequest.getParameter("code");
        if (!captchaId.equals(parameter)) {
            return false;
        } else {
            return true;
        }
    }
}
